/* Copyright (c) 2011 by Mani Brundha Kattamuri, Haritha Subramanyam
 *
 * Project Info:  http://code.google.com/p/andriod-travelapp-csc780/wiki/Design
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 */
package com.example.TravelApp.search.common.helper;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.TextView;

public class GeoCoderForLocationHelper {

	static TextView myLatitude;
	JSONObject json_data_invitation = new JSONObject();

	/**
	 * Establishes a HTTP connection and send the query URL to get the location
	 * co-ordinates for the location chosen by the user
	 * 
	 * @param address
	 *            - the area/location selected by user
	 * @return - the location co-ordinates
	 */
	public static String getLocationCoordinates(String address) {
		address = address.replaceAll(" ", "%20");
		String requestStr = getUrl(address);
		HttpGet httpGet = new HttpGet(requestStr);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);

			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return getGeoPoint(jsonObject);
	}

	/**
	 * Extracts the latitude and longitude of the of the address from the JSON
	 * response Latitude and longitude are converted to strings, concatenated
	 * and returned
	 * 
	 * @param jsonObject
	 * @return
	 */
	public static String getGeoPoint(JSONObject jsonObject) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lng");

			lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lat");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return lat.toString() + "," + lon.toString();

	}

	/**
	 * Constructs the URL which is used to request Google Maps for location
	 * co-ordinates depending on the address
	 * 
	 * @param toAddress
	 *            - address string
	 * @return - the URL to be sent to GeoCoder
	 */
	public static String getUrl(String toAdress) {
		StringBuffer urlString = new StringBuffer();
		urlString
				.append("http://maps.googleapis.com/maps/api/geocode/json?address=");
		urlString.append(toAdress.toString());
		urlString.append("&ka&sensor=false");
		return urlString.toString();
	}

}
